package com.bdqn.mongodb2.service;

import com.bdqn.mongodb2.entity.Book;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public List<Book> findAllBooks() {
        return mongoTemplate.findAll(Book.class, "mybook");
    }

    @Override
    public Book findBookById(int id) {
        return mongoTemplate.findById(id, Book.class, "mybook");
    }

    @Override
    public Book addBook(Book book) {
        return mongoTemplate.insert(book, "mybook");
    }

    @Override
    public UpdateResult updateBook(Book book) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(book.getId()));
        Update update = new Update();
        update.set("name", book.getName());
        update.set("author", book.getAuthor());
        update.set("category", book.getCategory());
        update.set("description", book.getDescription());
        update.set("imgurl", book.getImgurl());
        update.set("pnum", book.getPnum());
        update.set("price", book.getPrice());
        update.set("sale", book.getSales());
        return mongoTemplate.updateFirst(query, update, Book.class, "mybook");
    }

    @Override
    public DeleteResult deleteBook(int id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.remove(query, Book.class, "mybook");
    }

    //模糊查询
    @Override
    public List<Book> findLike(String name) {
        Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
        Query query = new Query(Criteria.where("name").regex(pattern));
        List<Book> bookList = mongoTemplate.find(query, Book.class, "mybook");
        return bookList;
    }

}
